import { Ref, onBeforeUnmount, onMounted } from "vue"
import { CurrentViewResult, EditCellStateResult, SelectCellStateResult } from "../state"

/**
 * 监听编辑元素以外的click事件，捕捉到时，重置选区、编辑状态。
 */
export function useListenDocumentClick(
    SelectState: SelectCellStateResult, 
    EditCellState: EditCellStateResult,
    currentView: CurrentViewResult,
    rootRef: Ref
) {
    const { resetEditState } = EditCellState
    const { resetSelectState } = SelectState
    const { tiggleCurrentView } = currentView

    const handel = () => {
        let target: HTMLElement | null = event?.target as HTMLElement
        do{
            if (target === rootRef.value) {
                // logInfo("在选区中")
                tiggleCurrentView(true)
                return;
            }
            target = target!.parentElement;
        } while(target && target?.tagName !== 'BODY')
        // logInfo("重置编辑状态以及选区了")
        resetEditState();
        resetSelectState();
        tiggleCurrentView(false)
    }
    const addDocumentClickListen = () => {
        window.addEventListener('click', handel)
    }
    const removeDocumentClickListen = () => {
        window.removeEventListener('click', handel)
    }
    onMounted(() => addDocumentClickListen())
    onBeforeUnmount(() => removeDocumentClickListen())

    return { currentView }
}